import datetime
import logging

import pandas as pd
from absl import app

from coin.base.datetime_util import to_datetime
from coin.feed.fastfeed.native_wrapper import run_from_feed_cache

from experimental.prophet.graph import graph
from experimental.prophet.graph_runner.fastfeed import (run_from_fastfeed_multiprocess,
                                                        FastfeedGraphAdapter)

from experimental.prophet.ops import globals
from experimental.prophet.ops.aggregator import scalar_value_aggregator
from experimental.prophet.ops.dataframe_feeder import dataframe_feeder
from experimental.prophet.ops.debug import printer
from experimental.prophet.ops.fastfeed import fastfeed_coin
from experimental.prophet.ops.timer import timer, custom_timer
from experimental.prophet.craps.universe import universe_btc


def model():
  ts = globals.global_timestamp()

  s_info = universe_btc()[1]
  feed = fastfeed_coin(s_info.product, s_info.sub_req, 'feed-01.ap-northeast-1.aws')
  bbo = graph.create_node('fastfeed.BookBestLevel', [feed.book])
  ask0_p = bbo.outputs[1].named_ref('xbtusd_ask0_p')
  bid0_p = bbo.outputs[3].named_ref('xbtusd_bid0_p')

  df = pd.DataFrame({'timestamp': [1554080400000001234, 1554080418313283123], 'a': [123.4, 234.5]})
  print(df)
  out = dataframe_feeder(df)

  with graph.control_if(out[-1]):
    printer('! %t %s %s %s', out[0], out[0], out[1], out[2])

  ts_10m = timer('60m')
  with graph.control_if(ts % (1 * 10**9) == 0):
    printer('%s %%t %%s' % s_info.nickname, ts, ts)
    # aggregator = scalar_value_aggregator([ts, ask0_p, bid0_p])


def main(argv):
  g = graph.Graph()
  with graph.as_default_graph(g):
    model()

  adapter = FastfeedGraphAdapter(g, 'feed-01.ap-northeast-1.aws')
  feed_sub_req = adapter.get_feed_sub_requests()

  run_from_feed_cache(feed_sub_req,
                      adapter.on_book_reset,
                      datetime.date(2019, 4, 1),
                      datetime.date(2019, 4, 2),
                      machine=adapter.default_machine)


if __name__ == '__main__':
  logging.basicConfig(
      level='DEBUG',
      format='%(levelname)8s %(asctime)s %(name)s %(filename)s:%(lineno)d] %(message)s')
  logging.getLogger('coin.exchange.util.feed_checker').setLevel(logging.WARNING)
  app.run(main)
